const express = require('express')
const router = express.Router()
const createError = require('http-errors')
const passport = require('passport')
const User = require('./mongoose')
const { getToken } = require('./authenticate')



router.post('/signup', (req, res, next) => {
    console.log(req.body)
    User.register(new User({ username: req.body.username }), req.body.password, (err, user) => {
        if (err) next(createError(403, '用户名已存在！'))
        else res.json({ user, msg: '注册成功!' })
        
    })
})

router.post('/login', passport.authenticate('local'), (req, res) => {
    const token = getToken({ _id: req.user._id })
    res.json({ user: req.user, msg: '登录成功!', token })
})

router.get('/logout', (req, res) => {
    req.session.destroy()
    res.end('退出成功!' )
})

module.exports = router